//
//  ApplyKi.m
//  BleKiSDK
//
//  Created by wulanzhou on 16/6/16.
//  Copyright © 2016年 wulanzhou. All rights reserved.
//

#import "ApplyKi.h"
#import "SkySimCardHandler.h"
#import "TCPManager.h"
#import "SkyTcpCmdDataPack.h"

@interface ApplyKi (){

    BOOL isLoading;
    
}
@property (nonatomic,strong) NSTimer *cardTimer;
@end


@implementation ApplyKi

- (id)init{

    if (self=[super init]) {
        isLoading=NO;
    }
    return self;
}


/**
 *  开始申请
 */
- (void)asyncApply{


    if ([BLECentralManager shareInstance].bluetoothState!=BLEStateOpen) {
        
        [self applyFinishWithKiData:nil success:NO message:@"蓝牙未打开，请确保打开后再试。"];
        
        return;
    }
    
    if (![[BLECentralManager shareInstance].getFirstConnector isConnected]) {
        [self applyFinishWithKiData:nil success:NO message:@"未能连接SkySim，请稍后再试。"];
        return;
    }
    
    if (isLoading) {
        return;
    }
    
    if (self.ipAddress&&[self.ipAddress isKindOfClass:[NSString class]]&&[self.ipAddress length]&&self.imsiData&&[self.imsiData isKindOfClass:[NSData class]]&&[self.imsiData length]>0) {
        
        isLoading=YES;
        [self getCardIdWithCompleted:^(NSData *cardId) {
            if (cardId) {
                [self downloadKiWithCardData:cardId];
            }
        }];
        
    }else{
        [self applyFinishWithKiData:nil success:NO message:@"参数错误"];
    }
}


/**
 *  下载ki
 *
 *  @param cardData
 */
- (void)downloadKiWithCardData:(NSData *)cardData{

    SkyTcpCmdDataPack *tcpCmdMod=[[SkyTcpCmdDataPack alloc] init];
    [tcpCmdMod downloadKiWithCardIDData:cardData withIMSIData:self.imsiData];
    
    //开始计时
    [self startTimer];
    [[TCPManager shareInstance] getKIFrom:self.ipAddress withPort:self.ipPort skyTcpCmdData:tcpCmdMod dataPackReceiveCompleted:^(SkyTcpCmdDataPack *decodeTcpDataPack) {

        if (decodeTcpDataPack&&[decodeTcpDataPack success]) {
            [self applyFinishWithKiData:[decodeTcpDataPack GetKiData] success:YES message:@"ki数据下载成功"];
            
        }else{
            
            NSString *str=@"ki数据下载失败";
            if (decodeTcpDataPack) {
                str=[NSString stringWithFormat:@"ki数据下载失败,状态码为：%@",decodeTcpDataPack.stateData];
            }
            [self applyFinishWithKiData:nil success:NO message:str];
            
        }
    }];
}



/**
 *  取得card id
 *
 *  @param completed 回调处理
 */
- (void)getCardIdWithCompleted:(void (^)(NSData *cardId))completed{

    static SkySimCardHandler *mod=nil;
    mod=[[SkySimCardHandler alloc] initWithCmd:[[SkyCmdGetCardID alloc] init]];
    [mod setSkySimReceiveDataCompletionBlock:^(SkySimCardData *decodeModel) {
        BOOL boo=NO;
        NSData *cardData=nil;
        if (decodeModel&&[decodeModel isKindOfClass:[SkyCmdGetCardID class]]) {
            SkyCmdGetCardID *item=(SkyCmdGetCardID*)decodeModel;
            cardData=item.bodyData;
            if (cardData) {
                boo=YES;
            }
            
        }
        if (!boo) {
            [self applyFinishWithKiData:nil success:NO message:@"取得卡片id未失败"];
        }
        
        if (completed) {
            completed(cardData);
        }
    }];
    [mod send];
}

- (void)applyFinishWithKiData:(NSData *)kiData success:(BOOL)success message:(NSString *)msg{
    
    NSLog(msg);
    
    [self stopTimer];
    isLoading=NO;
    if (self.KiDownloadCompletedBlock) {
        self.KiDownloadCompletedBlock(kiData,success);
    }
}

#pragma mark -计时处理
/**
 *  开始计时
 */
- (void)startTimer{
    [self stopTimer];
    self.cardTimer=[NSTimer scheduledTimerWithTimeInterval:30.0f target:self selector:@selector(cardIdLoadFinished) userInfo:nil repeats:NO];
    
}
/**
 *  停止计时
 */
- (void)stopTimer{
    if (self.cardTimer && [self.cardTimer isValid]) {
        [self.cardTimer invalidate];
    }
}

/**
 *  30秒内没有返回结果
 */
- (void)cardIdLoadFinished{
    //NSLog(@"%s", __FUNCTION__);
    [self applyFinishWithKiData:nil success:NO message:@"tcp服务器未响应"];
}

@end
